<template>
  <Transition name="fade">
    <div v-if="isVisible" class="fixed inset-0 z-40 bg-black/50" @click="handleOverlayClick">
      <Card
        v-if="isVisible"
        ref="cardRef"
        class="fixed left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 w-[680px] h-[600px] overflow-hidden rounded-md shadow-lg bg-white z-50"
        @click.stop
      >
        <!-- 搜索框 -->
        <Input
          v-model:value="searchText"
          placeholder="搜索聊天…"
          size="large"
          class="mb-4"
          allow-clear
        />

        <!-- 新聊天按钮 -->
        <div
          v-if="!searchText"
          class="flex items-center px-2 py-3 hover:bg-gray-100 cursor-pointer text-primary font-medium rounded-lg"
          @click="$emit('new-chat')"
        >
          <EditOutlined class="mr-2" />
          新聊天
        </div>

        <!-- 聊天记录列表 -->
        <div class="mt-4 mb-2 px-2 text-gray-500 text-sm">
          {{ searchText ? '搜索结果' : '聊天记录' }}
          {{ filteredConversations.length ? `(${filteredConversations.length})` : '' }}
        </div>
        <List>
          <template v-if="filteredConversations.length">
            <RecycleScroller
              class="h-[400px]"
              :items="filteredConversations"
              :item-size="52"
              key-field="key"
            >
              <template #default="{ item }">
                <ListItem
                  class="hover:bg-gray-100 cursor-pointer px-2 py-2 rounded-lg flex items-center gap-2 !text-gray-500 text-base"
                  @click="handleSelect(item)"
                >
                  <MessageOutlined class="text-base text-gray-500 flex-shrink-0" />
                  <span v-if="searchText" v-html="highlightText(item.label)" class="flex-1"></span>
                  <span v-else class="flex-1">{{ item.label }}</span>
                </ListItem>
              </template>
            </RecycleScroller>
          </template>
          <div v-else class="text-center text-gray-500 mt-8">
            <div v-if="!searchText">
              <Empty description="暂无聊天记录" />
            </div>
            <div v-else>
              <Empty description="未找到相关聊天记录" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
            </div>
          </div>
          <Spin v-if="loading" class="absolute bottom-10 w-full text-center" />
        </List>
      </Card>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { InputSearch, Input, Card, List, ListItem, Spin,Empty } from 'ant-design-vue'
import { EditOutlined, MessageOutlined } from '@ant-design/icons-vue'
import { RecycleScroller } from 'vue3-virtual-scroller'
import 'vue3-virtual-scroller/dist/vue3-virtual-scroller.css'
import { highlightSearchText } from '@/utils/highlight'
import type { ConversationsProps } from 'ant-design-x-vue'

const props = defineProps<{
  conversations: ConversationsProps['items']
}>()

const isVisible = defineModel()
const emits = defineEmits(['select', 'new-chat'])

const cardRef = ref(null)
const loading = ref(false)
const searchText = ref('')

watch(isVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      const input = document.querySelector('.ant-input') as HTMLInputElement
      input?.focus()
    })
  }
})
// 过滤并排序会话列表
const filteredConversations = computed(() => {
  if (!searchText.value) return props.conversations

  const searchLower = searchText.value.toLowerCase()
  return props.conversations
    .filter((item) => (item.label as string).toLowerCase().includes(searchLower))
    .sort((a, b) => {
      // 优先显示以搜索词开头的项
      const aStartsWith = (a.label as string).toLowerCase().startsWith(searchLower)
      const bStartsWith = (b.label as string).toLowerCase().startsWith(searchLower)
      if (aStartsWith && !bStartsWith) return -1
      if (!aStartsWith && bStartsWith) return 1
      return 0
    })
})

// 高亮搜索文本
const highlightText = (text: string) => {
  return highlightSearchText(text, searchText.value)
}

// 处理选择
const handleSelect = (item) => {
  emits('select', item.key)
  isVisible.value = false
}

// ESC 关闭功能
const handleKeyDown = (e) => {
  if (e.key === 'Escape' && isVisible.value) {
    isVisible.value = false
  }
}

// 点击遮罩层关闭
const handleOverlayClick = (e) => {
  if (e.target === e.currentTarget) {
    isVisible.value = false
  }
}

onMounted(async () => {
  window.addEventListener('keydown', handleKeyDown)
})

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
</script>

<style scoped></style>
